package org.xinjiang.data.migration.flush.service.impl;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xinjiang.data.migration.flush.convert.AreaFlushConvert;
import org.xinjiang.data.migration.flush.dto.res.FlushResultDTO;
import org.xinjiang.data.migration.flush.service.IAreaFlushService;
import org.xinjiang.data.migration.hainan.convert.FlushLogConvert;
import org.xinjiang.data.migration.hainan.entity.HnRegionEntity;
import org.xinjiang.data.migration.hainan.service.IFlushLogService;
import org.xinjiang.data.migration.hainan.service.IHnRegionService;
import org.xinjiang.data.migration.xinjiang.entity.XjAreaEntity;
import org.xinjiang.data.migration.xinjiang.service.IXjAreaService;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class AreaFlushServiceImpl implements IAreaFlushService {
    @Resource
    private IHnRegionService regionService;

    @Resource
    private IXjAreaService areaService;

    @Resource
    private AreaFlushConvert areaFlushConvert;

    @Autowired
    private IFlushLogService flushLogService;

    @Autowired
    private FlushLogConvert flushLogConvert;

    @Override
    public FlushResultDTO flush() {
        FlushResultDTO result = new FlushResultDTO();
        // 处理当前页的数据
        List<HnRegionEntity> regionEntityList = regionService.list();
        if (CollectionUtils.isNotEmpty(regionEntityList)) {
            List<XjAreaEntity> insertList = regionEntityList.stream().map(areaFlushConvert::convert).collect(Collectors.toList());
            this.processPageData(insertList, result);
        }
        log.warn("success+++++++++");
        return result;
    }

    public void processPageData(List<XjAreaEntity> insertList, FlushResultDTO flush) {
        if (CollectionUtils.isEmpty(insertList)) {
            return;
        }

        for (XjAreaEntity entity : insertList) {
            try {
                areaService.save(entity);
                flush.setSuccessCount(flush.getSuccessCount() + 1);
            } catch (Exception e) {
                log.error("e===========", e);
                flush.setErrCount(flush.getErrCount() + 1);
                flushLogService.save(flushLogConvert.convertArea(entity, e.getMessage()));
            }
        }
    }
}
